<?php
/**
 * Created by 橙橙同学.
 * User: 橙橙同学
 * Date: 2017/11/13
 * Time: 下午9:34
 */

function json($status, $msg, $data = array())
{
    $jsonData = array('status' => $status, 'msg' => $msg, 'data' => $data);
    return json_encode($jsonData);
}


function logs($line, $filename = 'test'){
    $dir = BM.'/logs/'.$filename.'/';
    if (createDir($dir)){
        $logs = new KLogger($dir.date('Y-m-d').'.log',KLogger::DEBUG);
        $logs->LogInfo($line);
    }
}

function http_get($url){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION,1);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

function http_post($url,$param){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    }
    if (is_string($param)) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach($param as $key=>$val){
            $aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_ENCODING, "");
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}


function https_request($url, $data,$signature)
{
    $time = time();
    $curl = curl_init();// 启动一个CURL会话
    // 设置HTTP头
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "User-Agent: openApi",
        "Content-Type: application/json; charset=utf-8",
        "accept-encoding: gzip,deflate",
        "time-stamp: ".$time,
        "data-signature: ".$signature
    ));
    curl_setopt($curl, CURLOPT_URL, $url);         // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);      // Post提交的数据包

    curl_setopt($curl, CURLOPT_POST, 1);        // 发送一个常规的Post请求

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 获取的信息以文件流的形式返回
    $output = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话

    return $output; // 返回数据
}